package com.wodwl.configuration;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.web.multipart.MultipartFile;

public class Helper {
	// 计算文件大小
	// bt字节参考量
	public static final long SIZE_BT = 1024L;
	// KB字节参考量
	public static final long SIZE_KB = SIZE_BT * 1024L;
	// MB字节参考量
	public static final long SIZE_MB = SIZE_KB * 1024L;
	// GB字节参考量
	public static final long SIZE_GB = SIZE_MB * 1024L;
	// TB字节参考量
	public static final long SIZE_TB = SIZE_GB * 1024L;

	/*
	 * rootDir为绝对地址如 D:/g305_upload_file/ path为相对路径 app/
	 */
	public static boolean uploadFile(MultipartFile file, String rootDir,
			String relativePath) {
		try {
			UploadFileNode.init();
			if (!file.isEmpty()) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				Date date = new Date();
				String filename = sdf.format(date) + date.getTime();

				String ext = file.getOriginalFilename();
				UploadFileNode.originalFileName = ext;
				ext = ext.substring(ext.lastIndexOf("."));
				UploadFileNode.ext = ext;
				filename = filename + ext;
				UploadFileNode.size = UploadFileNode.getFileSize(file);
				byte[] bs = file.getBytes();
				String path = rootDir + relativePath + filename;
				UploadFileNode.storeRelativePath = relativePath + filename;

				File dir = new File(rootDir + relativePath);
				if (!dir.exists()) {
					dir.mkdir();
				}

				OutputStream out = new FileOutputStream(path);
				out.write(bs);
				out.close();
				UploadFileNode.flag = true;
			}
		} catch (Exception e) {
			return false;

		}
		return UploadFileNode.flag;

	}

	public static class UploadFileNode {
		public static boolean flag = false;// 是否上传成功
		public static String originalFileName = null;
		public static String ext = null;
		public static String size = null;
		public static String storeRelativePath = null;

		public static void init() {
			flag = false;
			originalFileName = null;
			ext = null;
			size = null;
			storeRelativePath = null;
		}

		public static String getFileSize(MultipartFile f) {
			long size = f.getSize();

			if (size >= 0 && size < SIZE_BT) {
				return size + "B";
			} else if (size >= SIZE_BT && size < SIZE_KB) {
				return size / SIZE_BT + "KB";
			} else if (size >= SIZE_KB && size < SIZE_MB) {
				return size / SIZE_KB + "MB";
			}
			return new Long(size).toString();
		}

	}

}
